import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 原型设计模式，通俗点就是对象克隆
 * java自带的clone方法是浅复制
 * @author：涂有
 * @date 2017年6月30日 下午3:39:07
 */
public class Prototype implements Cloneable, Serializable{

	private static final long serialVersionUID = 1526179960971982806L;

	private String string;
	private SerializableObject obj;
	
	/**浅复制，子类可以改变方法返回值类型*/
	public Prototype clone() throws CloneNotSupportedException{
		return (Prototype)super.clone();
	}
	
	/**深复制，利用序列化技术*/
	public Prototype cloneDeep() throws IOException, ClassNotFoundException{
		ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
		ObjectOutputStream objectOutput = new ObjectOutputStream(byteArrayOutput);
		objectOutput.writeObject(this);
		
		ByteArrayInputStream byteArrayInput = new ByteArrayInputStream(byteArrayOutput.toByteArray());
		ObjectInputStream objectInput = new ObjectInputStream(byteArrayInput);
		return (Prototype)objectInput.readObject();
	}

	public String getString() {
		return string;
	}

	public void setString(String string) {
		this.string = string;
	}

	public SerializableObject getObj() {
		return obj;
	}

	public void setObj(SerializableObject obj) {
		this.obj = obj;
	}

	@Override
	public String toString() {
		return "Prototype [string=" + string + ", obj=" + obj + "]";
	}
}

class SerializableObject implements Serializable{

	private static final long serialVersionUID = 832797120030864269L;
}
